package com.heartech.prediciton_wx.service.token;

import com.google.gson.Gson;
import com.heartech.prediciton_wx.entity.qrcode.QrStrState;
import com.heartech.prediciton_wx.entity.qrcode.QrTicket;
import com.heartech.prediciton_wx.entity.token.AccessToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Slf4j
@Service
public class TicketService {
    public QrTicket getTicket(String postUrl, String postParams) {
        QrTicket responseObject = null;
        try {
            String jsonData = "{\"expire_seconds\": 604800, \"action_name\": \"QR_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": 123}}}";
            URL urlForGetRequest = new URL(postUrl + URLEncoder.encode(postParams, StandardCharsets.UTF_8));
            HttpURLConnection postCon = (HttpURLConnection) urlForGetRequest.openConnection();
            postCon.setRequestMethod("POST");
            postCon.setRequestProperty("Accept", "application/json");
            postCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            postCon.setDoOutput(true);

            // 发送请求数据
            OutputStreamWriter wr = new OutputStreamWriter(postCon.getOutputStream());
            wr.write(jsonData);
            wr.flush();

            int responseCode = postCon.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(postCon.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // 打印响应内容以进行调试
                log.info("Response from the server: " + response.toString());

                // 使用Gson解析JSON数据
                Gson gson = new Gson();
                responseObject = gson.fromJson(response.toString(), QrTicket.class);
                postCon.disconnect();
            } else {
                log.info("GET request not worked");
                postCon.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return responseObject;
    }
}
